package com.levy.contronller.javase.proxy.jdkDynamicProxy;

import com.levy.contronller.javase.proxy.Hello;
import com.levy.contronller.javase.proxy.HelloImpl;
import com.levy.contronller.javase.proxy.commonProxy.HelloProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by levy on 2019/6/16.
 */
public class DynamicProxy implements InvocationHandler {

    private Object target;

    public DynamicProxy(Object target) {
        this.target = target;
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy() {
        return (T) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();

        Object result = method.invoke(target, args);
        after();

        return result;
    }

    private void before() {
        System.out.println("before");
    }

    private void after() {
        System.out.println("after");
    }


    public static void main(String[] args) {

        System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        DynamicProxy dynamicProxy = new DynamicProxy(new HelloImpl());

//        Hello helloProxy = (Hello) Proxy.newProxyInstance(
//                hello.getClass().getClassLoader(),
//                hello.getClass().getInterfaces(),
//                dynamicProxy);


        Hello hello = dynamicProxy.getProxy();
        System.out.println(hello.getClass());
        System.out.println(hello.getClass().getSuperclass());
//
        hello.say("dsfdf");

    }
}
